package files

import (
	"database/sql"
	"os"
	"path/filepath"

	"gitee.com/xuender/oils/logs"
	"github.com/mattn/go-sqlite3"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// NewDBService 新建数据库.
func NewDB(ctx *Context) *gorm.DB {
	if fi, err := os.Lstat(ctx.DataBasePath); err == nil {
		if !fi.IsDir() {
			panic(ctx.DataBasePath + "不是目录")
		}
	} else if os.IsNotExist(err) {
		logs.Panic(os.MkdirAll(ctx.DataBasePath, 0755))
	}

	mode := logger.Silent
	if ctx.Debug {
		mode = logger.Info
	}

	file := "files.db"

	if ctx.HasRegexp {
		name := "sqlite3_regexp"
		sql.Register(name,
			&sqlite3.SQLiteDriver{
				Extensions: []string{
					"regexp",
				},
			})

		db, err := gorm.Open(&sqlite.Dialector{
			DriverName: name,
			DSN:        filepath.Join(ctx.DataBasePath, file),
		},
			&gorm.Config{
				Logger: logger.Default.LogMode(mode),
			})
		if err != nil {
			panic(err)
		}

		dbInit(db)

		return db
	}

	db, err := gorm.Open(sqlite.Open(filepath.Join(ctx.DataBasePath, file)),
		&gorm.Config{
			Logger: logger.Default.LogMode(mode),
		})
	if err != nil {
		panic(err)
	}

	dbInit(db)

	return db
}

// NewTestDB 测试数据库.
func NewTestDB() *gorm.DB {
	db, _ := gorm.Open(sqlite.Open("file::memory:"), &gorm.Config{})

	db.Debug()
	dbInit(db)

	return db
}

func dbInit(db *gorm.DB) {
	logs.Panic(db.AutoMigrate(&Config{}, &File{}))

	size := int64(0)

	db.Model(&Config{}).Count(&size)

	if size == 0 {
		for _, dir := range ignoreDirs {
			db.Save(&Config{
				Value: dir,
				Type:  ByteIgnore,
			})
		}
	}
}
